package com.example;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.amqp.rabbit.listener.adapter.MessageListenerAdapter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;

@Component
public class LogConsumer {

    @Autowired
    private DataSource dataSource;

    @RabbitListener(queues = "log_queue")
    public void receiveMessage(String message) {
        System.out.println(" [x] Received '" + message + "'");
        saveLogToDatabase(message);
    }

    private void saveLogToDatabase(String message) {
        try (Connection conn = dataSource.getConnection()) {
            String sql = "INSERT INTO logs (message) VALUES (?)";
            try (PreparedStatement stmt = conn.prepareStatement(sql)) {
                stmt.setString(1, message);
                stmt.executeUpdate();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Bean
    public Queue logQueue() {
        return new Queue("log_queue", true);
    }

    @Bean
    public DirectExchange logExchange() {
        return new DirectExchange("log_exchange", true, false);
    }

    @Bean
    public Binding binding(Queue logQueue, DirectExchange logExchange) {
        return BindingBuilder.bind(logQueue).to(logExchange).with("log_key");
    }

    @Bean
    public SimpleMessageListenerContainer messageListenerContainer(ConnectionFactory connectionFactory, MessageListenerAdapter listenerAdapter) {
        SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        container.setQueueNames("log_queue");
        container.setMessageListener(listenerAdapter);
        return container;
    }

    @Bean
    public MessageListenerAdapter listenerAdapter(LogConsumer receiver) {
        return new MessageListenerAdapter(receiver, "receiveMessage");
    }
}


